package com.tansuo365.test1.controller.kucunstuff;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tansuo365.test1.bean.kucunbean.WeixiuDetails;
import com.tansuo365.test1.bean.kucunbean.WeixiuZong;
import com.tansuo365.test1.service.kucunservice.WeixiuDetailsService;
import com.tansuo365.test1.service.kucunservice.WeixiuZongService;
import com.tansuo365.test1.service.kucunservice.WuliaoKucunRiZhiService;
import com.tansuo365.test1.util.DateUtil;
import com.tansuo365.test1.util.StringUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@PropertySource(value = "classpath:danhao.properties")
@Api(value = "维修单相关控制层", tags = "", description = "")
@RestController
@RequestMapping("/admin/weixiudan")
public class WeixiuDanController {

    @Autowired
    private WeixiuZongService weixiuZongService;
    @Autowired
    private WeixiuDetailsService weixiuDetailsService;
    @Autowired
    private WuliaoKucunRiZhiService wuliaoKucunRiZhiService;


    //    @Autowired
//    private WeixiuDetailsService weixiuDetailsService;
    @Value("${danhao.weixiudan.prefix}")
    private String weixiudanPrefix;

    //weixiu单号生成

    /**
     * 获取weixiu单号 OK
     *
     * @param type
     * @return
     * @throws Exception
     */
    @Async
    @RequestMapping("/getWeixiuNumber")
    public ListenableFuture<String> genBillCode(String type) throws Exception {
        StringBuffer billCodeStr = new StringBuffer();
        billCodeStr.append(weixiudanPrefix);
        billCodeStr.append(DateUtil.getCurrentDateStr());
        String todayMaxWeixiuDanNumber = weixiuZongService.getTodayMaxWeixiuDanNumber();
        if (todayMaxWeixiuDanNumber != null) {
            billCodeStr.append(StringUtil.formatCode(todayMaxWeixiuDanNumber));
        } else {
            billCodeStr.append("0001");
        }
        return new AsyncResult<>(billCodeStr.toString());
    }

    @RequestMapping("/getSelective")
    public Map<String, Object> getWeixiuDan(WeixiuZong weixiuZong, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "rows", required = true) Integer rows) {
        if (weixiuZong == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, rows);
        List<WeixiuZong> weixiuZongsList = weixiuZongService.listWeixiuZong(weixiuZong);
        PageInfo<WeixiuZong> pageInfo = new PageInfo<>(weixiuZongsList);
        resultMap.put("rows", pageInfo.getList());
        resultMap.put("total", pageInfo.getTotal());
        return resultMap;
    }

    @RequestMapping("/listDetailsByZId")
    public Map<String, Object> listDetailsByZongId(WeixiuDetails weixiuDetails, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "rows", required = true) Integer rows) {
        if (weixiuDetails == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, rows);
        List<WeixiuDetails> weixiuDetailsList = weixiuDetailsService.listWeixiuDetailsSelective(weixiuDetails);
        PageInfo<WeixiuDetails> pageInfo = new PageInfo<>(weixiuDetailsList);
        resultMap.put("rows", pageInfo.getList());
        resultMap.put("total", pageInfo.getTotal());
        return resultMap;
    }

    @RequestMapping("/save")
    public Map<String, Object> save(HttpSession session, WeixiuZong weixiuZong, @RequestParam("wuliaoWeixiuDetailsJson") String wuliaoWeixiuDetailsJson) {
        if (weixiuZong == null || wuliaoWeixiuDetailsJson == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        Gson gson = new Gson();
        List<WeixiuDetails> weixiuDetailsList = gson.fromJson(wuliaoWeixiuDetailsJson, new TypeToken<List<WeixiuDetails>>() {
        }.getType());
        weixiuZong.setChuangjianren((String) session.getAttribute("truename"));
        //save时, 先保存大表, 大表返回id后再保存附表
        int insertCode = weixiuZongService.saveZongAndDetails(weixiuZong, weixiuDetailsList);
        if (insertCode > 0) {
            resultMap.put("success", true);
            resultMap.put("msg", "保存成功.");
            return resultMap;
        } else if (insertCode == 0) {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "保存失败");
            return resultMap;
        }else if (insertCode < -99) {
            WeixiuDetails weixiuDetails = weixiuDetailsList.get((-insertCode) - 100);
            resultMap.put("success", false);
            resultMap.put("errorInfo", "保存失败,保存维修物料[" + weixiuDetails .getMingchengguige() + "]超过现有库存数量,请核对库存数量再进行出库操作.");
            return resultMap;
        } else {
            WeixiuDetails weixiuDetails = weixiuDetailsList.get((-(insertCode) - 1));
            resultMap.put("success", false);
            resultMap.put("errorInfo", "保存失败,保存物料[" + weixiuDetails.getMingchengguige() + "]不存在库存中.");
            return resultMap;
        }
    }

    @RequestMapping("/update")
    public Map<String, Object> update(WeixiuZong weixiuZong) {
        if (weixiuZong == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        int updateCode = weixiuZongService.updateByPrimaryKeySelective(weixiuZong);
        if (updateCode > 0) {
            resultMap.put("success", true);
            return resultMap;
        } else {
            resultMap.put("success", false);
            return resultMap;
        }
    }

    @RequestMapping("/delete")
    @Transactional
    public Map<String, Object> deleteBatch(@RequestParam("ids[]") Integer[] ids) {
        Map<String, Object> resultMap = new HashMap<>();
        if (ids == null) {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "请选中条目进行删除");
            return resultMap;
        }
        int ziDelCode = 0;
        int kucunhuifuCode = wuliaoKucunRiZhiService.insertAndDeletePosunOrWeixiuShu(ids, "weixiudan");
        int code = weixiuZongService.deleteBatchByPKArr(ids);  //批量删除weixiu主表
        if(code>0){
            ziDelCode = weixiuDetailsService.deleteByZongIdArr(ids); //批量删除weixiu详细根据ids条目
        }
        if (code > 0 && ziDelCode > 0 && kucunhuifuCode > 0) {
            resultMap.put("success", true);
        } else {
            resultMap.put("success", false);
        }
        return resultMap;
    }

    @RequestMapping("/repair/{weixiuzhuangtai}")
    public Map<String, Object> repairBatch(@RequestParam("ids[]") Integer[] ids, @PathVariable String weixiuzhuangtai) {
        Map<String, Object> resultMap = new HashMap<>();
        if (ids == null) {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "请选中条目进行操作");
            return resultMap;
        }
        if(weixiuzhuangtai==null){
            resultMap.put("success", false);
            resultMap.put("errorInfo", "维修状态异常");
            return resultMap;
        }
        System.out.println("weixiuzhuangtai:"+weixiuzhuangtai);

        //不删除维修单主表和子表,只更改其weixiuzhuangtai字段为'已修复'
        int kucunhuifuCode = 0;
        if(weixiuzhuangtai.equals("未修复")){
            kucunhuifuCode = wuliaoKucunRiZhiService.insertAndDeletePosunOrWeixiuShu(ids, "weixiufu");
        }else if(weixiuzhuangtai.equals("已修复")){
            kucunhuifuCode = wuliaoKucunRiZhiService.insertAndDelDaohuoShu(ids, "yixiufu");
        }else{
            resultMap.put("success", false);
            resultMap.put("errorInfo", "维修状态异常");
            return resultMap;
        }

        int upztCode = weixiuZongService.updateZhuangtaiByIds(ids);
        int updZtCode = weixiuDetailsService.updateDZhuangtaiByZIds(ids);

        if (upztCode > 0 && updZtCode > 0 && kucunhuifuCode > 0) {
            resultMap.put("success", true);
            return resultMap;
        } else {
            resultMap.put("success", false);
            return resultMap;
        }
    }
}
